package com.wocai.jrt.orgadmin.approve.action;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wocai.jrt.orgadmin.approve.bean.ApproveRoleReqBean;
import com.wocai.jrt.orgadmin.approve.bean.ApproveRoleType;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroup;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroupMember;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupMemberService;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupService;
import com.wocai.jrt.orgadmin.flow.model.Flow;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowService;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;

/**
 * 审批角色团队控制器
 * @author zhangyz
 * @date 2016-3-17 17:34:00
 */
@Controller
@RequestMapping("/approveRoleGroup")
public class ApproveRoleGroupAction extends GenericAction<ApproveRoleGroup> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ApproveRoleGroupAction.class);
	
	@Inject
	private ApproveRoleGroupService approveRoleGroupServiceImpl;
	@Inject
	private ApproveRoleGroupMemberService approveRoleGroupMemberServiceImpl;
	@Inject
	private FlowService flowServiceImpl;
	
	/**
     * 获得审批角色团队List，初始化列表页。
     * @param model 参数
     * @return 审批角色团队List
     */
    @RequestMapping("/list")
    public String initial(ApproveRoleGroup model, Map<String, Object> maps) {
        return "setting/approveRoleList";
    }
	
	/**
	 * 获得审批角色团队List，Json格式。
	 * @param model 参数
	 * @return 审批角色团队List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody ApproveRoleGroup model) {
		List<ApproveRoleGroup> list = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			list = approveRoleGroupServiceImpl.myPagedList(model);
			ApproveRoleGroupMember argp= new ApproveRoleGroupMember();
			for (ApproveRoleGroup arp : list) {
				argp.setApproveRoleGroupId(arp.getId());
				arp.setApproveRoleNum(approveRoleGroupMemberServiceImpl.pagedList(argp).size());
				if(1 == arp.getType()){
					arp.setTypeName(arp.getApproveName());
				}else{
					arp.setTypeName(ApproveRoleType.get(String.valueOf(arp.getType())));
				}
			}
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = approveRoleGroupServiceImpl.myPagedList(model).size();
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("get queryApproveRole list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得审批角色团队里具体成员列表。
	 * @param model 参数
	 * @return 审批角色团队成员List
	 */
	@ResponseBody
	@RequestMapping("/queryRole")
	public Map<String, Object> queryRole(@RequestBody ApproveRoleGroupMember model) {
		List<ApproveRoleGroupMember> list = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 统计的时候，不需要分页
			list = approveRoleGroupMemberServiceImpl.getApproveGroupEmpList(model);
			for (ApproveRoleGroupMember argm : list) {
				if(argm.getEmployeeId().equals(model.getEmployeeId())){
					argm.setIsPrincipal(true);
				}
			}
			model.setPage(null);
			long totalRecord = approveRoleGroupMemberServiceImpl.getApproveGroupEmpList(model).size();
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("get queryApproveRole member list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得审批角色团队中该项目的尽调小组成员列表。
	 * @param model 参数
	 * @return 审批角色团队尽调小组成员List
	 */
	@ResponseBody
	@RequestMapping("/querySurveyRole")
	public Map<String, Object> querySurveyRole(@RequestBody ApproveRoleGroupMember model) {
		List<ApproveRoleGroupMember> list = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			//获取当前项目的尽调小组负责人
			ApproveRoleGroup params = new ApproveRoleGroup();
			params.setProjectId(model.getId());
			params.setType(2);
			List<ApproveRoleGroup> argList = approveRoleGroupServiceImpl.pagedList(params);
			LOGGER.info("get querySurveyRole member list  params=[{}].",JSON.toJSONString(params));
			String groupId = "";
			String employeeId = "";
			if(argList.size() ==1){
				groupId = argList.get(0).getId();
				employeeId = argList.get(0).getEmployeeId();
			}
			ApproveRoleGroupMember  argmModel = new ApproveRoleGroupMember();
			argmModel.setId(groupId);
			list = approveRoleGroupMemberServiceImpl.getApproveGroupEmpList(argmModel);
			for (ApproveRoleGroupMember argm : list) {
				if(argm.getEmployeeId().equals(employeeId)){
					argm.setIsPrincipal(true);
				}
			}
			//统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = approveRoleGroupMemberServiceImpl.getApproveGroupEmpList(model).size();
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
			result.put("groupId",groupId);
		} catch (Exception e) {
			LOGGER.error("get queryApproveRole member list error, errorMsg=[{}].", e.getMessage());
		}
		return result;
	}
    
	 /**
	 * 为项目成立尽调小组
	 * 
	 * @param model
	 *            查询参数，携带ID
	 */
	@ResponseBody
	@RequestMapping("/createSurveyGroup")
	public JsonBean createSurveyGroup(@RequestBody ApproveRoleGroup model) {
		JsonBean bean = new JsonBean();
		try {
			if(StringUtils.isAnyBlank(model.getProjectId())){
				bean.setCode(0);
        		bean.setMessage("参数异常!");
        		LOGGER.info("createSurveyGroup, params is error =[{}]", JSON.toJSONString(model));
        		return bean;
			}
			//获取项目管理流程
			Flow flow = new Flow();
			flow.setFlowName("项目管理流程");
			flow.setOrgId(UserUtils.getOrgId());
			List<Flow> flowList = flowServiceImpl.pagedList(flow);
			if(flowList.size() != 1){
				bean.setCode(0);
        		bean.setMessage("获取项目管理流程失败!");
        		LOGGER.info("createSurveyGroup get project flow error,params is [{}]", JSON.toJSONString(flow));
        		return bean;
			}
			ApproveRoleGroup param = new ApproveRoleGroup();
			param.setProjectId(model.getProjectId());
			param.setType(2);
			param.setOrgId(UserUtils.getOrgId());
			param.setFlowId(flowList.get(0).getId());
			List<ApproveRoleGroup>  argList = approveRoleGroupServiceImpl.pagedList(param);
			//当前项目没有成立尽调小组时为项目成立尽调小组
			if(argList.size() == 0){
				model.setId(ObjectId.get().toString());
				model.setType(2);
				model.setOrgId(UserUtils.getOrgId());
				model.setFlowId(flowList.get(0).getId());
				LOGGER.info("create a new SurveyGroup for project,params is [{}]", JSON.toJSONString(flow));
				int result = approveRoleGroupServiceImpl.save(model);
				if(result == 1){
					bean.setCode(1);
	        		bean.setMessage("新增尽调小组成功!");
				}else{
					bean.setCode(0);
	        		bean.setMessage("新增尽调小组失败!");
				}
			}else{
				bean.setCode(1);
        		bean.setMessage("尽调小组已设置!");	
			}
		} catch (Exception e) {
			bean.setCode(0);
			LOGGER.error("createSurveyGroup , errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
		
    /**
     * 查看审批角色团队详情页。
     * @param model 查询参数，携带ID
     * @return 审批角色团队详情页
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id")String id, Map<String, Object> maps) {
    	try {
    		ApproveRoleGroup a = approveRoleGroupServiceImpl.get(id);
			a.setTypeName(ApproveRoleType.get(String.valueOf(a.getType())));
    		maps.put("model", a);
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "setting/approveRoleSet";
    }
    
    /**
     * 尽调小组审批角色分配添加成员
     * @param model
     * @return JsonBean
     */
    @ResponseBody
	@RequestMapping("/allotSurveyEmp")
	public JsonBean allotSurveyEmp(@RequestBody ApproveRoleReqBean model) {
    	JsonBean bean = new JsonBean();
		if(StringUtils.isAnyBlank(model.getEmployeeId(),model.getGroupId())){
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			LOGGER.info("approve allotSurveyEmp Role member params=[{}].",JSONObject.toJSONString(model));
			ApproveRoleGroupMember agm = new ApproveRoleGroupMember();
			agm.setApproveRoleGroupId(model.getGroupId());
			List<ApproveRoleGroupMember> list =approveRoleGroupMemberServiceImpl.pagedList(agm);
			Set<String> KeySet = new HashSet<String>();
			for (ApproveRoleGroupMember l: list) {
				KeySet.add(l.getEmployeeId());
			}
			if(KeySet.contains(model.getEmployeeId())){
				bean.setCode(2);
				bean.setMessage("该理财师已经在该审批分组中");
				return bean;
			}
			//当分配的是投资部时,判断该投资经理是否已经属于其他投资部门
			ApproveRoleGroup uniqueArg =approveRoleGroupServiceImpl.get(model.getGroupId());
			ApproveRoleGroup invest = approveRoleGroupServiceImpl.getInvestmentHead(model.getEmployeeId());
			if(invest != null && uniqueArg != null && uniqueArg.getType().equals("1")){
				bean.setCode(2);
				bean.setMessage("该理财师已经在其他投资部门中");
				return bean;
			}
			ApproveRoleGroupMember agmNew = new ApproveRoleGroupMember();
			agmNew.setId(ObjectId.get().toString());
			agmNew.setEmployeeId(model.getEmployeeId());
			agmNew.setApproveRoleGroupId(model.getGroupId());
			int result = approveRoleGroupMemberServiceImpl.save(agmNew);
			if(result == 1){
				bean.setCode(1);
				bean.setMessage("审批角色分配理财师成功");
			}else{
				bean.setCode(0);
				bean.setMessage("审批角色分配理财师失败");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage(e.getMessage());
			LOGGER.error("approve allotEmp Role member  error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
    
    /**
     * 审批角色分配添加成员
     * @param model
     * @return JsonBean
     */
    @ResponseBody
	@RequestMapping("/allotEmp")
	public JsonBean allotEmp(@RequestBody ApproveRoleReqBean model) {
    	JsonBean bean = new JsonBean();
		if(StringUtils.isAnyBlank(model.getEmployeeId(),model.getGroupId())){
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			LOGGER.info("approve allotSurveyEmp Role member params=[{}].",JSONObject.toJSONString(model));
			ApproveRoleGroupMember agm = new ApproveRoleGroupMember();
			agm.setApproveRoleGroupId(model.getGroupId());
			List<ApproveRoleGroupMember> list =approveRoleGroupMemberServiceImpl.pagedList(agm);
			Set<String> KeySet = new HashSet<String>();
			for (ApproveRoleGroupMember l: list) {
				KeySet.add(l.getEmployeeId());
			}
			if(KeySet.contains(model.getEmployeeId())){
				bean.setCode(2);
				bean.setMessage("该理财师已经在该审批分组中");
				return bean;
			}
			//当分配的是投资部时,判断该投资经理是否已经属于其他投资部门
			ApproveRoleGroup uniqueArg =approveRoleGroupServiceImpl.get(model.getGroupId());
			ApproveRoleGroup invest = approveRoleGroupServiceImpl.getInvestmentHead(model.getEmployeeId());
			if(invest != null && uniqueArg != null && uniqueArg.getType() == 1){
				bean.setCode(2);
				bean.setMessage("该理财师已经在其他投资部门中");
				return bean;
			}
			ApproveRoleGroupMember agmNew = new ApproveRoleGroupMember();
			agmNew.setId(ObjectId.get().toString());
			agmNew.setEmployeeId(model.getEmployeeId());
			agmNew.setApproveRoleGroupId(model.getGroupId());
			int result = approveRoleGroupMemberServiceImpl.save(agmNew);
			if(result == 1){
				bean.setCode(1);
				bean.setMessage("审批角色分配理财师成功");
			}else{
				bean.setCode(0);
				bean.setMessage("审批角色分配理财师失败");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage(e.getMessage());
			LOGGER.error("approve allotEmp Role member  error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
    
    /**
     * 终审审批角色添加成员
     * @param model
     * @return JsonBean
     */
    @ResponseBody
	@RequestMapping("/allotLastEmp")
	public JsonBean allotLastEmp(@RequestBody ApproveRoleReqBean model) {
    	JsonBean bean = new JsonBean();
		if(StringUtils.isAnyBlank(model.getEmployeeId(),model.getGroupId())){
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			ApproveRoleGroupMember agm = new ApproveRoleGroupMember();
			agm.setApproveRoleGroupId(model.getGroupId());
			List<ApproveRoleGroupMember> list =approveRoleGroupMemberServiceImpl.pagedList(agm);
			Set<String> KeySet = new HashSet<String>();
			for (ApproveRoleGroupMember l: list) {
				KeySet.add(l.getEmployeeId());
			}
			if(KeySet.contains(model.getEmployeeId())){
				bean.setCode(2);
				bean.setMessage("该理财师已经在终审审批分组中");
				return bean;
			}
			//移除之前成员关系
			ApproveRoleGroupMember agmDelete = new ApproveRoleGroupMember();
			agmDelete.setApproveRoleGroupId(model.getGroupId());
			approveRoleGroupMemberServiceImpl.deleteBulks(agmDelete);
			//添加成员关系
			ApproveRoleGroupMember agmNew = new ApproveRoleGroupMember();
			agmNew.setId(ObjectId.get().toString());
			agmNew.setEmployeeId(model.getEmployeeId());
			agmNew.setApproveRoleGroupId(model.getGroupId());
			int result = approveRoleGroupMemberServiceImpl.save(agmNew);
			//设置为负责人
			ApproveRoleGroup arg = new ApproveRoleGroup();
			arg.setEmployeeId(model.getEmployeeId());
			arg.setId(model.getGroupId());
			result = approveRoleGroupServiceImpl.updateById(arg);
			if(result == 1){
				bean.setCode(1);
				bean.setMessage("分配项目最终审批人成功");
			}else{
				bean.setCode(0);
				bean.setMessage("分配项目最终审批人失败");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage(e.getMessage());
			LOGGER.error("approve allotEmp Role member  error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
    
    /**
     * 审批角色成员设置
     * @param model
     * @return JsonBean
     */
    @ResponseBody
	@RequestMapping("/roleSet")
	public JsonBean roleSet(@RequestBody ApproveRoleReqBean model) {
    	JsonBean bean = new JsonBean();
		if(StringUtils.isAnyBlank(model.getEmployeeId(),model.getGroupId())){
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			int result = 0;
			switch (model.getType()) {
			//移除成员
			case 1:
				ApproveRoleGroupMember  params = new ApproveRoleGroupMember();
				params.setEmployeeId(model.getEmployeeId());
				params.setApproveRoleGroupId(model.getGroupId());
				result = approveRoleGroupMemberServiceImpl.deleteBulks(params);
				break;
			//设为负责人	
			case 2:	
				ApproveRoleGroup arg = new ApproveRoleGroup();
				arg.setEmployeeId(model.getEmployeeId());
				arg.setId(model.getGroupId());
				result = approveRoleGroupServiceImpl.updateById(arg);
				break;
			//取消负责人
			case 3:
				ApproveRoleGroup arg_2 = new ApproveRoleGroup();
				arg_2.setId(model.getGroupId());
				arg_2.setEmployeeId("");
				result = approveRoleGroupServiceImpl.updateById(arg_2);
				break;
			default:
				break;
			}
			if(result == 1){
				bean.setCode(1);
				bean.setMessage("审批角色成员设置成功");
			}else{
				bean.setCode(0);
				bean.setMessage("审批角色成员设置失败");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage(e.getMessage());
			LOGGER.error("approve roleSet  error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
    
    /**
     * 新增投资部
     *  @param ApproveRoleReqBean
     *  @return JsonBean
     */
    @ResponseBody
   	@RequestMapping("/addGroup")
   	public JsonBean addGroup(@RequestBody ApproveRoleGroup model) {
    	JsonBean bean = new JsonBean();
    	try {
			ApproveRoleGroup arp = new ApproveRoleGroup();
			arp.setApproveName(model.getApproveName());
			arp.setType(1);
			List<ApproveRoleGroup>  list = approveRoleGroupServiceImpl.pagedList(arp);
			if(list.size() > 0){
				bean.setCode(0);
				bean.setMessage("该投资不名称已经存在!");
				return bean;
			}
			arp.setId(ObjectId.get().toString());
			arp.setOrgId(UserUtils.getOrgId());
			int result = approveRoleGroupServiceImpl.save(arp);
			if(result == 1){
				bean.setCode(1);	
				bean.setMessage("新增投资部成功!");
			}else{
				bean.setCode(0);
				bean.setMessage("新增投资部失败!");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage(e.getMessage());
		}
    	return bean;
    }
}
